package com.orhon.smartcampus.modules.systemctl.fetcher;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.modules.systemctl.dao.ApisDao;
import com.orhon.smartcampus.modules.systemctl.entity.Apis;
import com.orhon.smartcampus.modules.systemctl.entity.Modules;
import com.orhon.smartcampus.modules.systemctl.gqlModel.GQLApis;
import com.orhon.smartcampus.modules.systemctl.gqlModel.GQLModule;
import com.orhon.smartcampus.modules.systemctl.mm.ApisMapper;
import com.orhon.smartcampus.modules.systemctl.mm.ModuleMapper;
import com.orhon.smartcampus.utils.ObjectToMap;
import com.orhon.smartcampus.utils.Util;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class ApisFetcher implements DataFetcher {


    @Autowired
    ApisDao apisDao;

    /**
     * 获取部门列表
     *
     * @param environment
     * @return
     * @throws Exception editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        List<GQLApis> gqlApis = new ArrayList<>();

        GQLPageParam page = EnvArgsMapper.MAPPER.fromArgs(environment);
        String hql = "from Apis where deleted_at = null";

        if (environment.containsArgument("condition")) {
            HashMap<String, Object> map = ObjectToMap.to(environment.getArgument("condition"));
            if (map.get("id") != null) {
                hql += " and id =" + map.get("id");
            }
            if (map.get("module_id") != null) {
                hql += " and module_id " + Util.decide(map.get("module_id"));
            }

        }
        List<Apis> list = apisDao.find(hql, null, page.getPage(), page.getLimit());


        for (Apis item : list) {
        	
        	GQLModule gqlModule = null;
			if (environment.getSelectionSet().contains("data/module")){
				Modules modules = item.getModule();
				gqlModule = ModuleMapper.MAPPER.mapModule(modules);
			}
        	
            GQLApis apis = ApisMapper.MAPPER.toApis(item);
            apis.setModule(gqlModule);
            gqlApis.add(apis);
           
        }

        Long total = 0L;
        if (environment.getSelectionSet().contains("total")) {
            total = apisDao.getTotalCount(hql);
        }
        return Result.ok().put("data", gqlApis).put("total", total);
    }
}
